<?php
/**
 * Created by PhpStorm.
 * User: poptser@foxmail.com
 * Date: 2018/4/16
 * Time: 16:07
 */
namespace App\Services\Sorting;

use App\Services\SortingWeb\OrderService as SortingOrder;
use App\Services\Orders\OrderService as Order;
use App\Services\SortingWeb\ToolService;
use http\Exception;
use Illuminate\Support\Facades\DB;

class SortingNewService
{


    public $sortingOrder;   //配货 order service
    public $order;          //主order service
    public $toolService;    //辅助工具 service

    public function __construct(SortingOrder $sortingOrder, Order $order,
                                ToolService $toolService)
    {

        $this->sortingOrder = $sortingOrder;
        $this->order = $order;
        $this->toolService = $toolService;

    }

    /**
     * 获取公司列表
     * Author:poptser@foxmail.com
     * @return mixed
     */
    public function getCompanyList()
    {
        $companyList = DB::table('distribution_company')->where('status', 0)
            ->select(['id', 'lite_name'])->get()->toArray();

        $companyList[] = (Object)[
            'id' => 0,
            "lite_name" => "自配送"
        ];
        return $companyList;
    }


    public function buildSql($date=null,$companyId=null, $time=null,
                             $zone=null,$wid){

    }



    /**
     * 获取指定区域订单数
     * Author:poptser@foxmail.com
     * @param $date
     * @param null $companyId
     * @param null $time
     * @param null $zone
     * @param  $wid
     * @return mixed
     */
    public function getOrderNum($date=null,$companyId=null, $time=null,
                                $zone=null,$wid){
        $sqlBase = "SELECT COUNT('id') AS num FROM sdx_order_info AS oi LEFT JOIN sdx_sorting_order_link AS sol ON oi.order_id = sol.order_id WHERE";
        $sqlBase .=" oi.shipping_id = 3 AND oi.shipping_status = 0 AND oi.pay_status IN (2, 3) AND oi.order_status != 2 AND sol.order_id IS NULL";
        $sqlBase .=" AND oi.k3cn_sn IS NOT NULL AND oi.wid = ".$wid;

        if(isset($companyId)){
            $sqlBase .=" AND oi.distribution_company_id = ".$companyId;
        }
        if(!empty($zone)){
            $wdr_id_array = DB::table("warehouse_deliver_region")->where("zoning_id","=",$zone)->pluck('id')->toArray();
            $sqlBase .=" AND oi.wdr_id in (".implode(',',$wdr_id_array).")";
        }

        if(!empty($date)){
            if(!empty($time)){
                //已传入时间
                if($time!="超时订单"){
                    //正常时间
                    $dis_time = explode("-",$time);
                    $sqlToday =$sqlBase." AND oi.best_time_start = '".strtotime($date." ".$dis_time[0])."' AND oi.best_time = '".strtotime($date." ".$dis_time[1])."'";
                }else{
                    //超时订单
                    $sqlToday =$sqlBase." AND TO_DAYS(from_unixtime(oi.best_time, '%Y%m%d')) < TO_DAYS('".$date."')";
                }
                //$filter[] = ['best_time', '=', $time];
            }else{
                //未传入时间
                $sqlToday =$sqlBase." AND oi.best_time  BETWEEN ".strtotime($date)." AND ".strtotime($date." 23:59:59");
            }
        }else{
            $sqlToday =$sqlBase;
        }

        $todayNum = DB::selectOne($sqlToday);
        //dump($sqlToday);
        $numDate['today'] =  $todayNum->num;

        if(!empty($date)){
            if(!empty($time)){
                //已传入时间
                if($time=="超时订单"){
                    $sqlOtherday =$sqlBase." AND oi.best_time  BETWEEN ".strtotime($date)." AND ".strtotime($date." 23:59:59");
                }else{
                    //正常时间
                    $sqlOtherday =$sqlBase." AND TO_DAYS(from_unixtime(oi.best_time, '%Y%m%d')) < TO_DAYS('".$date."')";
                }
            }else{
                //未传入时间
                $sqlOtherday =$sqlBase." AND (best_time_start > '".strtotime($date." 23:59:59")."' OR best_time_start < '".strtotime($date)."')";
            }

            $otherTodayNum = DB::selectOne($sqlOtherday);
            $numDate['otherToday'] =  $otherTodayNum->num;
        }
        return $numDate;

    }

    /**
     * 获取配送时间分组
     * Author:poptser@foxmail.com
     * @param $date
     * @param null $companyId
     * @param null $zone
     * @param $wid
     * @return mixed
     */
    public function getDistributionTime($date, $companyId = null, $zone = null, $wid)
    {
        //条件总成
        $sqlBase = "SELECT best_time_start,best_time FROM sdx_order_info AS oi LEFT JOIN sdx_sorting_order_link AS sol ON oi.order_id = sol.order_id WHERE";
        $sqlBase .=" oi.shipping_id = 3 AND oi.shipping_status = 0 AND oi.pay_status IN (2, 3) AND oi.order_status != 2 AND sol.order_id IS NULL";
        $sqlBase .=" AND oi.k3cn_sn IS NOT NULL AND oi.wid = ".$wid;

        if(isset($companyId)){
            $sqlBase .=" AND oi.distribution_company_id = ".$companyId;
        }
        if(!empty($zone)){
            $wdr_id_array = DB::table("warehouse_deliver_region")->where("zoning_id","=",$zone)->pluck("id")->toArray();
            $sqlBase .=" AND oi.wdr_id in (".implode(',',$wdr_id_array).")";
        }
        if(!empty($date)){
            $sqlBase .=" AND oi.best_time  BETWEEN ".strtotime($date)." AND ".(strtotime($date) + 3600*24)." GROUP BY best_time_start,best_time";

        }

        //DB::enableQueryLog();
        return DB::select($sqlBase);
        //return DB::getQueryLog();
    }

    /**
     * 获取区域列表
     * Author:poptser@foxmail.com
     * @param $date
     * @param null $companyId
     * @param null $time
     * @param $wid
     * @return mixed
     */
    public function getDistributionZone($date, $companyId = null, $time = null, $wid)
    {
        //条件总成
        $sqlBase = "SELECT wdr_id FROM sdx_order_info AS oi LEFT JOIN sdx_sorting_order_link AS sol ON oi.order_id = sol.order_id WHERE";
        $sqlBase .=" oi.shipping_id = 3 AND oi.shipping_status = 0 AND oi.pay_status IN (2, 3) AND oi.order_status != 2 AND sol.order_id IS NULL";
        $sqlBase .=" AND oi.k3cn_sn IS NOT NULL AND oi.wid = ".$wid;

        if(isset($companyId)){
            $sqlBase .=" AND oi.distribution_company_id = ".$companyId;
        }
        if(!empty($zone)){
            $wdr_id_array = DB::table("warehouse_deliver_region")->where("zoning_id","=",$zone)->pluck("id")->toArray();
            $sqlBase .=" AND oi.wdr_id in (".implode(',',$wdr_id_array).")";
        }
        if(!empty($date)&&!empty($time)){
            $dis_time = explode("-",$time);
            if(count($dis_time)>1){
                $sqlBase .= " AND oi.best_time_start = '".strtotime($date." ".$dis_time[0])."' AND oi.best_time = '".strtotime($date." ".$dis_time[1])."'";
            }else{
                $sqlBase .= " AND ( oi.best_time_start > '".strtotime($date." 23:59:59")."' OR oi.best_time < '".strtotime($date)."')";
            }

        }
        $sqlBase .= " GROUP BY wdr_id";

        //DB::enableQueryLog();
        //return $sqlBase;


        $WdrList = DB::select($sqlBase);

        $wdrArray = [];
        foreach ($WdrList as $wdr){
            $wdrArray[] = $wdr->wdr_id;
        }
        if(count($wdrArray)>0){
            $ZoneList = DB::table('warehouse_deliver_region')->whereIn("id",$wdrArray)->groupBy("zoning_id")->select(['zoning_id as area_id','name'])->get();
            foreach ($ZoneList as $value) {
                //转换区域名称
                $value->name = $this->toolService->getAreaName($value->area_id);
            }
            return $ZoneList;
        }else{
            return [];
        }


        //return DB::getQueryLog();
    }

    /**
     * 生成一个拣货单
     * Author:poptser@foxmail.com
     * @param $date
     * @param $companyId
     * @param $time
     * @param $zone
     * @param $wid
     * @param $userId
     * @return mixed
     */
    public function setSortingOrder($date, $companyId, $time, $zone, $wid,$userId)
    {
        $sorting_id = 0;

        //条件总成
        $sqlBase = "SELECT oi.order_id,oi.order_status,oi.shipping_status,oi.pay_status";
        $sqlBase .= " FROM sdx_order_info AS oi LEFT JOIN sdx_sorting_order_link AS sol ON oi.order_id = sol.order_id WHERE";
        $sqlBase .=" oi.shipping_id = 3 AND oi.shipping_status = 0 AND oi.pay_status IN (2, 3) AND oi.order_status != 2 AND sol.order_id IS NULL";
        $sqlBase .=" AND oi.k3cn_sn IS NOT NULL AND oi.wid = ".$wid;

        if(isset($companyId)){
            $sqlBase .=" AND oi.distribution_company_id = ".$companyId;
        }
        if(!empty($zone)){
            $wdr_id_array = DB::table("warehouse_deliver_region")->where("zoning_id","=",$zone)->pluck("id")->toArray();
            //return $wdr_id_array;
            $sqlBase .=" AND oi.wdr_id in (".implode(',',$wdr_id_array).")";
        }
        if(!empty($date)&&!empty($time)){
            $dis_time = explode("-",$time);
            if(count($dis_time)>1){
                $sqlBase .= " AND oi.best_time_start = '".strtotime($date." ".$dis_time[0])."' AND oi.best_time = '".strtotime($date." ".$dis_time[1])."'";
            }else{
                $sqlBase .= " AND ( oi.best_time_start > '".strtotime($date." 23:59:59")."' OR oi.best_time < '".strtotime($date)."')";
            }
        }

        $ToolService = new ToolService();

        $max_num = $ToolService->getSortingMaxNum($wid);
        if(empty($max_num)){
            $max_num = 5;
        }
        $sqlBase .= " LIMIT ".$max_num;


        $orderList = DB::select($sqlBase);

        if(count($orderList)>0){
            $sortingSn = get_order_sn();
            $sorting_id = DB::table('sorting_order')->insertGetId(
                [
                    'sorting_sn' => $sortingSn,
                    'status' => 1,
                    'ctime' => gm_time(),
                    'user_id' => $userId,
                    'wid' => $wid,
                    'best_date' => $date,
                    'best_time' => $time,
                    'area_id' => $zone,
                    'company_id' => $companyId
                ]
            );
            if($sorting_id>0){
                $order_link_data = [];
                foreach ($orderList as $value){
                    $dataAction['order_status'] = $value->order_status;
                    $dataAction['shipping_status'] = $value->shipping_status;
                    $dataAction['pay_status'] = $value->pay_status;
                    $dataAction['action_user'] = $ToolService->getNameById($userId);
                    $dataAction['order_id']=$value->order_id;
                    $dataAction['action_note']='已生成拣货单:'.$sortingSn." [ SortingWeb ]";;
                    $dataAction['log_time']=gm_time();
                    $dataAction['user_id']=$userId;
                    $this->order->addOrderAction($dataAction);
                    $order_link_data[] = ['order_id' =>$value->order_id, 'sorting_order_id' =>$sorting_id];
                }
                DB::table('sorting_order_link')->insert($order_link_data);
            }
        }

        if($sorting_id>0){
            $sortingOrder = DB::table("sorting_order")->where("id",$sorting_id)->first();
            return $sortingOrder;
        }else{
            return false;
        }



    }
}